<template>
  <div>
    <!-- 选择框 -->
    <el-card>
      <CategoySelector @changeCategoryId='changeCategoryId' ref="cs" />
    </el-card>

    <!-- 表格 -->
    <el-card>
      <div v-show="!isShowAddOrUpdateAttr">
        <el-button type="primary" icon="el-icon-plus" style="margin-bottom:20px" @click="showAddAttr"
          :disabled='!category3Id'>
          添加属性
        </el-button>

        <!-- 平台属性 -->
        <el-table :data="attrList" border stripe style="width: 100%;">
          <el-table-column type="index" label="序号" width="100" align='center'>
          </el-table-column>
          <el-table-column label="属性名称" width="150">
            <template slot-scope="{row}">
              <el-badge :value="row.attrValueList.length" class="item">
                <el-button size="small">{{row.attrName}}</el-button>
              </el-badge>
            </template>
          </el-table-column>
          <el-table-column label="属性值列表">
            <template slot-scope="{row}">
              <el-tag type="success" v-for="item in row.attrValueList" :key="item.id">{{item.valueName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="{row}">
              <HintButton title="修改属性" size="mini" type="primary" icon="el-icon-edit" @click="showUpdateAttr(row)" />
              <el-popconfirm :title="`您确定删除${row.attrName}吗？`" @onConfirm='deleteAttr(row.id)'>
                <HintButton title="删除属性" size="mini" type="danger" icon="el-icon-delete" slot="reference" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="isShowAddOrUpdateAttr">
        <el-form inline :model="formData">
          <!-- 属性名称 -->
          <el-form-item label="属性名称">
            <el-input type="text" v-model="formData.attrName" placeholder="请输入属性名称"></el-input>
          </el-form-item>
        </el-form>
        <!-- 两个按钮 -->
        <div style="margin-bottom:20px">
          <el-button type="primary" icon="el-icon-plus" @click="addAttrValue"
            :disabled='!formData.attrName.trim().length'>添加属性值</el-button>
          <el-button @click="isShowAddOrUpdateAttr=false">取消</el-button>
        </div>
        <!-- 表格 -->
        <el-table :data="formData.attrValueList" border stripe style="width: 100%;" v-loading="loding">
          <el-table-column type="index" label="序号" width="80" align='center'>
          </el-table-column>
          <el-table-column label="属性值名称">
            <template slot-scope="{row, $index}">
              <el-input type="text" v-model="row.valueName" placeholder="请输入属性值" size="mini" v-if="row.edit"
                :ref="$index" @blur="toView(row)" @keyup.native.enter="toView(row)">
              </el-input>
              <span v-else @click="toEdit(row, $index)"
                style="width:100%;display:inline-block;">{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template slot-scope="{row,$index}">
              <el-popconfirm :title="`您确定删除${row.valueName}吗？`" @onConfirm='deleteValue($index)'>
                <HintButton size="mini" type="danger" icon="el-icon-delete" title="删除属性值" slot="reference" />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 两个按钮 -->
        <div style="margin-bottom:20px">
          <el-button type="primary" @click="save" :disabled='!isSaveValid'>保存</el-button>
          <el-button @click="isShowAddOrUpdateAttr=false">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
  import cloneDeep from 'lodash/cloneDeep';
  export default {
    name: 'Attr',
    data() {
      return {
        category1Id: '', //一级分类id
        category2Id: '', //二级分类id
        category3Id: '', //三级分类id
        attrList: [], //平台属性数组
        isShowAddOrUpdateAttr: false, //控制添加或修改平台属性值的界面的标识
        loding: false,
        formData: {
          attrName: '', // 平台属性名字
          attrValueList: [] // 平台属性值对象数组
        }
      }
    },
    methods: {
      //选中的分类内容改变时的回调函数
      changeCategoryId({
        level,
        categoryId
      }) {
        switch (level) {
          case 1:
            this.category1Id = categoryId;
            //重置二级三级分类的id和平台属性
            this.category2Id = null;
            this.category3Id = null;
            this.attrList = [];
            break
          case 2:
            this.category2Id = categoryId;
            this.category3Id = null;
            this.attrList = [];
            break
          case 3:
            this.category3Id = categoryId;
            this.attrList = [];
            this.loding = true;
            this.getAttrList();
            break
        }
      },
      //获取平台属性数据
      async getAttrList() {
        let result = await this.$API.attr.getAttrInfoList(this.category1Id, this.category2Id, this.category3Id);
        this.loding = false;
        if (result.code == 200) {
          //跟新数据
          this.attrList = result.data;
        }
      },
      //点击修改属性按钮，显示修改平台属性按钮
      showUpdateAttr(attrInfo) {
        //更新传入过来的数据(深拷贝)
        this.formData = cloneDeep(attrInfo);
        //显示界面
        this.isShowAddOrUpdateAttr = true;
      },
      // 点击添加属性值按钮的事件的回调函数
      addAttrValue() {
        this.formData.attrValueList.push({
          attrId: this.formData.id,
          valueName: '',
          edit: true
        });
        this.$nextTick(() => {
          this.$refs[this.formData.attrValueList.length - 1].focus();
        })
      },
      //查看模式
      toView(attrValue) {
        // 判断文本框中是否有数据,此时没有数据,则不会变成查看模式
        if (!attrValue.valueName.trim()) return;
        // 此时有数据,但是新录入的数据和之前已经存在的数据不能一样
        if (this.formData.attrValueList.filter(item => item.valueName == attrValue.valueName).length == 2) {
          this.$message.warning('请勿重复输入！！');
          return;
        }
        // 此时说明,数据存在,并且有效,变成查看模式
        attrValue.edit = false;
      },
      //编辑模式
      toEdit(attrValue, index) {
        // 判断数据里是否有edit属性,没有则添加一个响应式的属性
        if (!attrValue.hasOwnProperty('edit')) {
          this.$set(attrValue, 'edit', true);
        } else {
          attrValue.edit = true;
        }
        //在页面加载之后获取到这个元素
        this.$nextTick(() => {
          this.$refs[index].focus(); //获取焦点
        });
      },
      //删除某个属性值的操作
      deleteValue(index) {
        this.formData.attrValueList.splice(index, 1); //删除掉在选中的元素
        this.$message.success('删除成功');
      },
      //保存操作
      async save() {
        //如果属性名为空,返回
        if (!this.formData.attrName.trim()) {
          this.$message.warning('属性名不能为空！！');
          return
        };
        this.formData.attrValueList = this.formData.attrValueList.filter(item => {
          delete item.edit; //删除掉edit属性
          return !!item.valueName.trim(); //如果属性为空则过滤掉
        });
        // 如果属性值列表没有内容
        if (this.formData.attrValueList.length === 0) {
          this.$message.warning('至少添加一个属性值！！');
          return
        }
        //发送接口请求
        const result = await this.$API.attr.addOrUpdateAttrInfo(this.formData);

        if (result.code !== 200) {
          this.$message.error('操作失败！！');
          return
        }
        this.$message.success('操作成功！！');
        this.isShowAddOrUpdateAttr = false; //添加属性界面隐藏
        this.getAttrList(); //刷新数据
      },
      //删除属性
      async deleteAttr(id) {
        //发送接口请求
        const result = await this.$API.attr.deleteAttrInfoById(id);
        if (!result.code == 200) {
          this.$message.error('操作失败！！');
        }
        this.$message.success('操作成功');
        this.getAttrList();
      },
      showAddAttr() {
        this.formData = {
          attrName: '', //属性名字
          attrValueList: [], //属性值对象的数组
          categoryId: this.category3Id, // 三级分类的id
          categoryLevel: 3 //级别是3
        };
        this.isShowAddOrUpdateAttr = true;
      }
    },
    watch: {
      //修改属性的时候三级导航不可修改
      isShowAddOrUpdateAttr(val) {
        this.$refs.cs.isDisabled = val;
      }
    },
    computed: {
      isSaveValid() {
        return this.formData.attrName.trim() && this.formData.attrValueList.some(item => item.valueName.trim());
      }
    }
  }

</script>

<style>
  .item {
    margin-top: 10px;
    margin-right: 40px;
  }

</style>
